local modname = minetest.get_current_modname()


local tree_textures = {"default_tree_top.png", "default_tree.png", "default_leaves.png"}

player_api.register_model("tree.b3d", {
	animation_speed = 1,
	textures = tree_textures,
	animations = {
		-- Standard animations.
		stand     = {x = 0,   y = 1},
		lay       = {x = 0,   y = 1},
		walk      = {x = 0,   y = 1},
		mine      = {x = 0,   y = 1},
		walk_mine = {x = 0,   y = 1},
		sit       = {x = 0,   y = 1},
	},
	collisionbox = {-0.3, 0.0, -0.3, 0.3, 1.7, 0.3},
	stepheight = 0.6,
	eye_height = 1.47,
})

local armor_3d = false

if minetest.get_modpath("3d_armor") then
	armor_3d = true

	local old_update_player_visuals = armor.update_player_visuals
	armor.update_player_visuals = function(self, player)
		if player_api.get_animation(player).model == "tree.b3d" then
			if not player then
				return
			end
			local name = player:get_player_name()
			if self.textures[name] then
				default.player_set_textures(player, tree_textures)
			end
			self:run_callbacks("on_update", player)
		else
			return old_update_player_visuals(self, player)
		end
	end
end


local function set_roots(player)
	local pos = player:get_pos()
	pos.x = math.floor(pos.x + 0.5)
	pos.z = math.floor(pos.z + 0.5)
	player:set_pos(pos)

	player:set_look_horizontal(minetest.dir_to_yaw(minetest.wallmounted_to_dir(minetest.dir_to_wallmounted(minetest.yaw_to_dir(player:get_look_horizontal())))))
end

local players = {}

local function treensform(player)
	local name = player:get_player_name()
	players[name] = player_api.get_animation(player)
	player_api.set_model(player, "tree.b3d")
	player_api.set_textures(player, tree_textures)
end

local function untreensform(player)
	local name = player:get_player_name()

	player_api.set_model(player, players[name].model)
	player_api.set_textures(player, players[name].textures)

	players[name] = nil
end

minetest.register_on_leaveplayer(function(player, timed_out)
	local name = player:get_player_name()
	players[name] = nil
end)


minetest.register_craftitem(modname .. ":forest_wand", {
	description = "Living Branch \nPunch to treenform \nUse to set roots",
	inventory_image = "treensformation_wand.png",
	stack_max = 1,
	on_place = function(itemstack, placer, pointed_thing)
		set_roots(placer)
	end,
	on_secondary_use = function(itemstack, user, pointed_thing)
		set_roots(user)
	end,
	on_use = function(itemstack, user, pointed_thing)
		if player_api.get_animation(user).model ~= "tree.b3d" then
			treensform(user)
		else
			untreensform(user)
		end
	end,
})
